<template>
  <div class="fault-recommendation q-pa-md">
    <h5 class="q-mt-none q-mb-md">故障处理推荐</h5>

    <!-- 故障类型选择 -->
    <div class="row q-mb-md">
      <q-select
        v-model="selectedKeyword"
        :options="keywords"
        label="选择故障类型"
        outlined
        dense
        class="col-12"
        @input="fetchRecommendations"
      />
    </div>

  <!-- 故障描述输入 
   <div class="row q-mb-md">
     <q-input
       v-model="faultDescription"
       outlined
       dense
       label="输入故障描述关键词（可选）"
       class="col-grow"
     >
       <template v-slot:append>
         <q-btn
           color="primary"
           icon="search"
           flat
           dense
           @click="fetchRecommendations"
         />
       </template>
     </q-input>
   </div>
   -->

    <!-- 加载状态显示 -->
    <div v-if="loading" class="text-center q-pa-md">
      <q-spinner color="primary" size="3em" />
      <div class="q-mt-sm">正在加载推荐结果...</div>
    </div>

    <!-- 错误信息显示 -->
    <q-banner v-if="error" class="bg-negative text-white q-mb-md">
      {{ error }}
    </q-banner>

    <!-- 推荐结果展示 -->
    <div v-if="recommendations.length && !loading" class="recommendations-list q-mt-md">
      <div class="text-h6 q-mb-md">处理措施推荐</div>
      <q-list bordered separator>
        <q-item v-for="(rec, index) in recommendations" :key="index">
          <q-item-section>
            <q-item-label class="text-weight-medium">
              {{ index + 1 }}. 故障原因
            </q-item-label>
            <q-item-label caption class="q-pl-md">
              {{ rec.原因 }}
            </q-item-label>
            <q-item-label class="text-weight-medium q-mt-sm">
              处理措施
            </q-item-label>
            <q-item-label caption class="q-pl-md">
              {{ rec.措施 }}
            </q-item-label>
          </q-item-section>
        </q-item>
      </q-list>
    </div>

    <!-- 无数据提示 -->
    <div v-if="!loading && !recommendations.length && searched" class="text-center q-mt-lg">
      <q-icon name="info" size="2em" color="grey-7" />
      <div class="text-grey-7 q-mt-sm">未找到相关的处理措施推荐</div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'FaultRecommendation',
  data () {
    return {
      keywords: ['光路中断', '中兴传输系统', '华为传输系统', '动环监控', '保护装置', '主用光路'],
      selectedKeyword: '光路中断',
      faultDescription: '',
      recommendations: [],
      loading: false,
      error: null,
      searched: false
    }
  },
  created () {
    this.fetchRecommendations()
  },
  methods: {
    async fetchRecommendations () {
      this.loading = true
      this.error = null
      this.searched = true
      
      try {
        // 使用选中的故障类型，如果有额外的描述则附加上
        const fault = this.faultDescription 
          ? `${this.selectedKeyword} ${this.faultDescription}`
          : this.selectedKeyword

        const response = await axios.get('http://1.95.80.5:5000/recommend_solutions', {
          params: {
            fault: fault
          }
        })
        
        // 解析返回的文本数据
        const textData = response.data
        this.parseRecommendations(textData)
      } catch (err) {
        this.error = '获取推荐失败：' + (err.message || '未知错误')
        console.error('Error fetching recommendations:', err)
      } finally {
        this.loading = false
      }
    },
    parseRecommendations (textData) {
      // 将文本按照 ================ 分割获取主要内容
      const mainContent = textData.split('='.repeat(50))[1]
      if (!mainContent) {
        this.recommendations = []
        return
      }

      // 解析推荐列表
      const recommendations = []
      let currentRec = null

      mainContent.split('-'.repeat(40)).forEach(block => {
        const lines = block.trim().split('\n')
        if (lines.length >= 2) {
          const cause = lines[0].replace(/^\d+\.\s*原因:\s*/, '').trim()
          const solution = lines[1].replace(/^\s*措施:\s*/, '').trim()
          if (cause && solution) {
            recommendations.push({
              原因: cause,
              措施: solution
            })
          }
        }
      })

      this.recommendations = recommendations
    }
  }
}
</script>

<style scoped>
.fault-recommendation {
  max-width: 1200px;
  margin: 0 auto;
}

.recommendations-list {
  background: white;
  border-radius: 4px;
  padding: 16px;
}

.q-item-label.caption {
  font-size: 14px;
  line-height: 1.5;
  white-space: normal;
}
</style> 